package com.faceCaptor.main;

import com.faceCaptor.util.FileUtil;
import com.ha.facecamera.configserver.ConfigServer;
import com.ha.facecamera.configserver.pojo.Face;
import com.ha.sdk.util.IDGenerater;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class AddFaceDialog {
	
	private static final Logger log=Logger.getLogger(AddFaceDialog.class);
	private byte[] faceImageData;
	
	private Face ftu;
	public Face getFaceToUpload() {
		return ftu;
	}
	
	public AddFaceDialog(){
		
	}
	public AddFaceDialog(byte[] faceImageData) {
		this();
		//			lblImage.setIcon(new ImageIcon(zoomImage(ImageIO.read(new ByteArrayInputStream(faceImageData)), 200, 100)));
		this.faceImageData = faceImageData;
	}
	public  Face addFaceFromCaptureData(ConfigServer configServer,String sn, byte[] featureImageData, String id) {

		if (sn == null || sn.isEmpty())
			return null;
		AddFaceDialog afd = new AddFaceDialog(featureImageData);
		// afd.setVisible(true);
		// Face face = afd.getFaceToUpload();
		Face face = new Face();
		if (id != null) {
			face.setId(id);
		} else {
			face.setId(IDGenerater.generateShortID());
		}

		
		String separator = File.separator;
		String filePath ="web"+separator+"www";
		File filedir = new File(filePath);
		if (!filedir.exists()) {
				filedir.mkdirs();
		}
		
		String filename = UUID.randomUUID().toString()+".png";
		String path = filePath+separator+filename;
		log.info("文件路径："+path);
		face.setJpgFilePath(new String[] { path });
		face.setJpgFileContent(new byte[][] {featureImageData});
		face.setName("wwb");
		FileUtil.save(filePath, filename, featureImageData);
		Date d = Calendar.getInstance().getTime();
		log.error(String.format("%tF %tT.%tL sn=>%s tid=>%d add face", d, d, d, sn, Thread.currentThread().getId()));
		// cs.addFace(sn, face, 5000);

		if (face == null)
			return null;
		if (!configServer.addFace(sn, face, 5000)) {
			log.error("注册人脸失败,向sn为" + sn + "的设备添加人脸失败！");
			log.error(configServer.getLastErrorMsg());
			return null;
		} else {
			log.info("注册人脸成功,设置sn为" + sn + "的设备添加人脸成功！" + face.toJson());
			
			
		}
		d = Calendar.getInstance().getTime();
		log.error(String.format("%tF %tT.%tL sn=>%s tid=>%d add face ret=>code:%d msg:%s", d, d, d, sn,
				Thread.currentThread().getId(), configServer.getLastErrorCode(), configServer.getLastErrorMsg()));
		return face;
	}


}
